package com.itms.service;

import com.itms.entity.InterfaceLog;
import com.itms.mapper.InterfaceLogMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Date;
import java.util.List;

@Service
public class LogService {

    @Autowired
    private InterfaceLogMapper interfaceLogMapper;

    /**
     * 保存接口日志异常
     * @param e
     * @param type 类型
     */
   public void saveLog(Exception e,String type,String className){

       InterfaceLog interfaceLog = new InterfaceLog();
       String msg =  getStackMsg(e);

       if (msg.length()>3000)
           msg = msg.substring(0,3000);

       interfaceLog.setClassName(className);
       interfaceLog.setMsg(msg);
       interfaceLog.setStatus("error");
       interfaceLog.setCreatedTime(new Date());
       interfaceLog.setType(type);
       this.interfaceLogMapper.insertSelective(interfaceLog);


    }

    /**
     *
     * @param e
     * @param type
     * @param className
     * @param code
     */
    public void saveDetailLog(Object e,String type,String className,String code){
        InterfaceLog interfaceLog = new InterfaceLog();
        InterfaceLog log=interfaceLogMapper.getLogByDataCode(code);
        if(log==null){
            interfaceLog.setDataCode(code);
            interfaceLog.setClassName(className);
            interfaceLog.setMsg(e.toString());
            interfaceLog.setCreatedTime(new Date());
            interfaceLog.setType(type);
            interfaceLog.setStatus("error");
            this.interfaceLogMapper.insertSelective(interfaceLog);
        }

    }

    /**
     *
     * @param list
     * @param type
     */
    public void saveErrorList(List list, String type ,String className){
        InterfaceLog interfaceLog = new InterfaceLog();

        String msg = "";
        String status="";

        if (list.size()>0){
            for (Object o:list) {
                msg += o.toString();

            }

            status="error";
            interfaceLog.setStatus(status);
        }else {
            msg = "succeed";
            status="succeed";
            interfaceLog.setStatus(status);
        }

        if (msg.length()>3000){
            msg = msg.substring(0,3000);
        }


        interfaceLog.setMsg(msg);
        interfaceLog.setCreatedTime(new Date());
        interfaceLog.setClassName(className);
        interfaceLog.setType(type);
        this.interfaceLogMapper.insertSelective(interfaceLog);



    }
    private static String getStackMsg(Exception e) {
        try {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            e.printStackTrace(pw);
            return "\r\n" + sw.toString() + "\r\n";
        } catch (Exception e2) {
            return "bad getErrorInfoFromException";
        }
    }
}
